package com.controller.common;

import com.common.utils.Constants;
import com.common.ErrorCodeEnum;
import com.model.base.Result;
import com.common.config.Config;
import com.common.exception.BusinessException;
import com.common.utils.file.FileUploadUtils;
import com.common.utils.file.FileUtils;
import com.common.utils.ServerConfig;
import com.common.utils.StringUtils;
import com.core.springSecurity.service.PermissionService;
import com.model.vo.sys.common.UploadFileVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

/**
 * 通用请求处理
 * 
 *
 */
@Api(tags = {"公共"})
@Slf4j
@RestController
@RequestMapping("/v1")
public class CommonController
{
   // private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    @Resource
    private ServerConfig serverConfig;

    /**
     * 通用上传请求
     */
    @ApiOperation(value = "文件上传请求")
    @PostMapping("/common/upload")
    @PreAuthorize("@ss.hasAnyPermi('" + PermissionService.SYSTEM_OPERATE + "')")
    public Result<UploadFileVO> uploadFile(MultipartFile file)
    {
        try {
            // 上传文件路径
            String filePath = Config.getUploadPath();
            // 上传并返回资源路径
            String resourcePath = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + resourcePath;
            return Result.suc(UploadFileVO.builder().resourcePath(resourcePath).url(url).build());
        }
        catch (Exception e) {
            return Result.fail(ErrorCodeEnum.UPLOAD_FILE);
        }
    }

    /**
     * 本地资源通用下载
     */
    @ApiOperation(value = "资源下载请求")
    @GetMapping("/common/download")
    @PreAuthorize("@ss.hasAnyPermi('" + PermissionService.SYSTEM_OPERATE + "')")
    public void resourceDownload(
            @ApiParam(name = "resource",value = "文件路径", required = true) @RequestParam("resourcePath") String resourcePath,
            @ApiParam(name = "delete",value = "是否删除", required = true) @RequestParam("delete") Boolean delete,
            HttpServletResponse response)
    {
        try
        {
            if (!FileUtils.checkAllowDownload(resourcePath))
            {
                throw new Exception(StringUtils.format("资源文件({})非法，不允许下载。 ", resourcePath));
            }
            // 数据资源地址
            String localPath = Config.getLocalFilePath() + StringUtils.substringAfter(resourcePath, Constants.RESOURCE_PREFIX);
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(localPath, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(localPath, response.getOutputStream());
            if (StringUtils.isNotNull(delete) && delete)
            {
                log.info("删除文件:{}",localPath);
                FileUtils.deleteFile(localPath);
            }
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
            throw new BusinessException(ErrorCodeEnum.FAILED);
        }
      //  return Result.suc();
    }
}
